﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using SCSService;

namespace SCS.Core.Models.ModelsFontend
{
    public class ShoppingCart
    {
        public string shoppingCartId { get; set; }
        public const string CartSessionKey = "CartId";

        #region "Cart"
        public static ShoppingCart GetCart(HttpContextBase context)
        {
            var cart = new ShoppingCart();
            cart.shoppingCartId = cart.GetCartId(context);
            return cart;
        }

        //using HttpContextBase to allow access to cookies.
        public String GetCartId(HttpContextBase context)
        {
            if (context.Session[CartSessionKey] == null)
            {
                if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
                {
                    // User is logged in, associate the cart with there username
                    context.Session[CartSessionKey] = context.User.Identity.Name;
                }
                else
                {
                    // Generate a new random GUID using System.Guid Class
                    Guid tempCartId = Guid.NewGuid();

                    // Send tempCartId back to client as a cookie
                    context.Session[CartSessionKey] = tempCartId.ToString();
                }
            }
            return context.Session[CartSessionKey].ToString();
        }

        public void AddToCart(SCSService.Product product)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            var cartItem = cartSvc.GetCartByCartIdAndProductID(shoppingCartId, product);

            if (cartItem == null)
            {
                // Create a new cart item
                cartItem = new SCSService.Cart
                {
                    ProductID=product.ProductID,
                    CartID = shoppingCartId,
                    Count = 1,
                    DateCreate=DateTime.Now
                };
                //DB AddToCarts(cartItem);
                cartSvc.AddToCart(cartItem);
            }
            else
            {
                // Add one to the quantity
                cartItem.Count++;
            }

            //Update to CartItem
            cartSvc.UpdateQuantityCart(cartItem);
           
        }

        public void RemoveFromCart(int recordId)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            //Get the cart
            var cartItem = cartSvc.GetCartByCartIdAndRecordID(shoppingCartId, recordId);

            if (cartItem != null)
            {
                if (cartItem.Count > 1)
                {
                    cartItem.Count--;
                    //Update to CartItem
                    cartSvc.UpdateQuantityCart(cartItem);
                }
                else
                {
                    //storeDB.Carts.DeleteObject(cartItem);
                    cartSvc.DeleteCartItem(cartItem);
                }
                
            }
        }

        public void DeleteCartItem(Cart cartItem)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            cartSvc.DeleteCartItem(cartItem);
        }
        //Clear Cart with one shoppingCartID
        public void EmptyCart()
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            var cartItems = cartSvc.GetListCartItemByShoppingCartID(shoppingCartId);

            foreach (var item in cartItems)
            {
                
                cartSvc.DeleteCartItem(item);
            }
        }

        //List CartItem 
        public List<SCSService.Cart> GetListCartItemByCartID()
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            return cartSvc.GetListCartItemByShoppingCartID(shoppingCartId);
        }

        //TotalValue of CartItem
        public double GetTotalValueCartItem(int? languageId)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            return cartSvc.GetTotal(shoppingCartId, languageId);
        }

        //Count CartItem
        public int GetCountCartItem()
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            return cartSvc.GetCountCartItem(shoppingCartId);
        }

        public int CreateOrder(SCSService.Customer_Order order,int? languageId)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            SCSService.ProductService proSvc = new SCSService.ProductService();
            double orderTotal = 0;

            var cartItems = cartSvc.GetListCartItemByShoppingCartID(shoppingCartId);
            int? currencyID = null;

            //Iterate the items in the cart, adding Order Details for each
            foreach (var item in cartItems)
            {
                var orderDetail = new SCSService.Order_Item()
                {
                    ProductID=item.ProductID,
                    OrderID=order.OrderID,
                    Quantity=item.Count,
                    CreateDate=DateTime.Now,
                    OrderItemStatus=0,          //0 la Start
                    UnitPrice = float.Parse(proSvc.GetProductPriceByProductID((int)item.ProductID, languageId, currencyID).PriceValue != null ? proSvc.GetProductPriceByProductID((int)item.ProductID, languageId, currencyID).PriceValue.ToString() : "0"),
                    Unit = proSvc.GetProductPriceByProductID((int)item.ProductID, languageId, currencyID).CurrencyID != null ? StockModel.GetCurrencyByID((int)proSvc.GetProductPriceByProductID((int)item.ProductID, languageId, currencyID).CurrencyID).CurrencyCode : ""
                };

                int orderItemID= cartSvc.CreateOrderDetail(orderDetail);
                
                /////////////////////////////////////////////////////////////////////////////////
                ///Chỉ áp dụng cho web bán mã thẻ
                //Create Order_Item_Deatail for website Card (Code and serial)
                //Select List Stock of Product in cart
               
                //SCSService.Product_Stock proStock = proSvc.GetProductInStockByProductID((int)item.ProductID,1,1);
                //Select list "Quantity" Product_Stock_Detail 
                //List<SCSService.Product_Stock_Detail> listDeatil = proSvc.GetListNoProductStockDetail((int)item.Count, proStock.StockID);
                List<SCSService.Product_Stock_Detail> listDeatil = proSvc.GetListNoProductStockDetailByProductID((int)item.ProductID, (int)item.Count, 1, 1);
                if (listDeatil.Count > 0)
                {
                    //foreach (var itemDetail in listDeatil)
                    //{
                    //    //Create Order_Item_Detail
                    //    SCSService.Order_Item_Detail detail = new SCSService.Order_Item_Detail()
                    //    {
                    //        ProductStockDetailID = itemDetail.ProductStockDetailID,
                    //        OrderItemID = orderItemID
                    //    };

                    //    int orderItemDeatilID = cartSvc.CreateOrderItemDetail(detail);
                    //    //Update status for Product Stock Detail
                    //    //status =2 product dang bi giu
                        
                    //    itemDetail.Status = 2;
                    //    UpdateStatusProductStockDetail(itemDetail);
                    //}

                    for (int i = 0; i < item.Count;i++ )
                    {
                        //Create Order_Item_Detail
                        SCSService.Order_Item_Detail detail = new SCSService.Order_Item_Detail()
                        {
                            ProductStockDetailID = listDeatil.ElementAt(i).ProductStockDetailID,
                            OrderItemID = orderItemID
                        };

                        int orderItemDeatilID = cartSvc.CreateOrderItemDetail(detail);

                        listDeatil.ElementAt(i).Status = 2;
                        listDeatil.ElementAt(i).ChangeStatusDate = DateTime.Now;    //Ghi lại thời điểm bắt đầu lock mã thẻ
                        UpdateStatusProductStockDetail(listDeatil.ElementAt(i));
                    }
                }
                
                //////////////////////////////////////////////////
            }

            orderTotal = cartSvc.GetTotal(shoppingCartId, languageId);
            order.Total = orderTotal;
            cartSvc.UpdateTotalOrder(order.OrderID, orderTotal);

            ////Empty the shopping cart
            //EmptyCart();

            //Return the OrderId as a confirmation number
            return order.OrderID;
        }

        public int CreateOrderTransfer(SCSService.Customer_Order order, int? languageId)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            SCSService.ProductService proSvc = new SCSService.ProductService();
            double orderTotal = 0;

            //var cartItems = cartSvc.GetListCartItemByShoppingCartID(shoppingCartId);
            //int? currencyID = null;

            //Iterate the items in the cart, adding Order Details for each
            //foreach (var item in cartItems)
            //{
            //    var orderDetail = new SCSService.Order_Item()
            //    {
            //        ProductID = item.ProductID,
            //        OrderID = order.OrderID,
            //        Quantity = item.Count,
            //        CreateDate = DateTime.Now,
            //        OrderItemStatus = 0,          //0 la Start
            //        UnitPrice = float.Parse(proSvc.GetProductPriceByProductID((int)item.ProductID, languageId, currencyID).PriceValue != null ? proSvc.GetProductPriceByProductID((int)item.ProductID, languageId, currencyID).PriceValue.ToString() : "0"),
            //        Unit = proSvc.GetProductPriceByProductID((int)item.ProductID, languageId, currencyID).CurrencyID != null ? StockModel.GetCurrencyByID((int)proSvc.GetProductPriceByProductID((int)item.ProductID, languageId, currencyID).CurrencyID).CurrencyCode : ""
            //    };

            //    int orderItemID = cartSvc.CreateOrderDetail(orderDetail);

            //    /////////////////////////////////////////////////////////////////////////////////
            //    ///Chỉ áp dụng cho web bán mã thẻ
            //    //Create Order_Item_Deatail for website Card (Code and serial)
            //    //Select List Stock of Product in cart

            //    //SCSService.Product_Stock proStock = proSvc.GetProductInStockByProductID((int)item.ProductID,1,1);
            //    //Select list "Quantity" Product_Stock_Detail 
            //    //List<SCSService.Product_Stock_Detail> listDeatil = proSvc.GetListNoProductStockDetail((int)item.Count, proStock.StockID);
            //    List<SCSService.Product_Stock_Detail> listDeatil = proSvc.GetListNoProductStockDetailByProductID((int)item.ProductID, (int)item.Count, 1, 1);
            //    if (listDeatil.Count > 0)
            //    {
            //        //foreach (var itemDetail in listDeatil)
            //        //{
            //        //    //Create Order_Item_Detail
            //        //    SCSService.Order_Item_Detail detail = new SCSService.Order_Item_Detail()
            //        //    {
            //        //        ProductStockDetailID = itemDetail.ProductStockDetailID,
            //        //        OrderItemID = orderItemID
            //        //    };

            //        //    int orderItemDeatilID = cartSvc.CreateOrderItemDetail(detail);
            //        //    //Update status for Product Stock Detail
            //        //    //status =2 product dang bi giu

            //        //    itemDetail.Status = 2;
            //        //    UpdateStatusProductStockDetail(itemDetail);
            //        //}

            //        for (int i = 0; i < item.Count; i++)
            //        {
            //            //Create Order_Item_Detail
            //            SCSService.Order_Item_Detail detail = new SCSService.Order_Item_Detail()
            //            {
            //                ProductStockDetailID = listDeatil.ElementAt(i).ProductStockDetailID,
            //                OrderItemID = orderItemID
            //            };

            //            int orderItemDeatilID = cartSvc.CreateOrderItemDetail(detail);

            //            listDeatil.ElementAt(i).Status = 2;
            //            listDeatil.ElementAt(i).ChangeStatusDate = DateTime.Now;    //Ghi lại thời điểm bắt đầu lock mã thẻ
            //            UpdateStatusProductStockDetail(listDeatil.ElementAt(i));
            //        }
            //    }

            //    //////////////////////////////////////////////////
            //}

            orderTotal = cartSvc.GetTotal(shoppingCartId, languageId);
            order.Total = orderTotal;
            cartSvc.UpdateTotalOrder(order.OrderID, orderTotal);

            ////Empty the shopping cart
            //EmptyCart();

            //Return the OrderId as a confirmation number
            return order.OrderID;
        }

        // When a user has logged in, migrate their shopping cart to
        // be associated with their username
        public void MigrateCart(string userName)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            var cartItems = cartSvc.GetListCartItemByShoppingCartID(shoppingCartId);

            foreach (var item in cartItems)
            {
                item.CartID = userName;
                cartSvc.UpdateCartId(item);
            }
        }

        public static SCSService.Cart GetCartbyRecordID(int recordID)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            return cartSvc.GetCartByRecordID(recordID);
        }

        public static void UpdateStatusProductStockDetail(Product_Stock_Detail stockDetail)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            cartSvc.UpdateStatusProductStockDetail(stockDetail);
        }

        public static List<Cart> GetListCartItemByShoppingCartID(string shoppingCartId)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            return cartSvc.GetListCartItemByShoppingCartID(shoppingCartId);
        }
        #endregion


        #region "Checkout"
        public static int AddOrder(SCSService.Customer_Order order)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            return cartSvc.AddOrder(order);
        }

        public static SCSService.Customer_Order GetCusOrderByOrderIdAndCustomerID(int orderID, int customerID)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            return cartSvc.GetCustomerOrderByOrderIDAndCustomerID(orderID, customerID);
        }

        public static int AddShipment(SCSService.Shipment ship)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            return cartSvc.AddShipment(ship);
        }

        public List<SCSService.Config_Payment_Method_Website> GetListPaymentMethod(int siteGuid)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            return cartSvc.GetListPaymentMethod(siteGuid);
        }

        public static SCSService.Config_Payment_Method_Website GetConfigPaymentMethod(int id)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            return cartSvc.GetConfigPaymentMethod(id);
        }

        public static SCSService.Payment_Method GetPaymentMethod(int id)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            return cartSvc.GetPaymentMethod(id);
        }

        public static string LoadRate(string currencyCode)
        {

            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load("http://www.vietcombank.com.vn/ExchangeRates/ExrateXML.aspx");
            XmlNode node = xmldoc.SelectSingleNode("ExrateList/Exrate[@CurrencyCode='" + currencyCode + "']");
            if (node != null)
            {
                XmlNode valueAttribute = node.Attributes.GetNamedItem("Transfer");
                if (valueAttribute != null)
                {
                    return valueAttribute.InnerXml;
                }
                return "0";
            }
            else
                return "0";
        }
        public static Invoice GetInvoiceByInvoiCode(string invoiceCode)
        {

            SCSService.CartService cartSvc = new SCSService.CartService();
            return cartSvc.GetInvoiceByInvoiCode(invoiceCode);
        }
        public static long CreateInvoice(SCSService.Invoice invoice)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            return cartSvc.CreateInvoice(invoice);
        }

        public int GetCountProductInOrder(int orderID)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            return cartSvc.GetCountProductInOrder(orderID);
        }

        public static SCSService.Customer_Order GetOrderByID(int orderID)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            return cartSvc.GetOrderByID(orderID);
        }

        public static SCSService.Invoice GetInvoiceByOrderID(int orderID)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            return cartSvc.GetInvoiceByOrderID(orderID);
        }

        public static void UpdateTempOrderIDforCart(SCSService.Cart cartItem)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            cartSvc.UpdateTempOrderIDforCart(cartItem);
        }

        public static SCSService.Cart GetCartByCartID(string CartID)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            return cartSvc.GetCartByCartID(CartID);
        }

        public static List<Cart> GetListCartItemsByCartID(string CartID)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            return cartSvc.GetListCartItemsByCartID(CartID);
        }

        public static void UpdateInvoiceStatus(SCSService.Invoice invoice)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            cartSvc.UpdateInvoiceStatus(invoice);
        }

        public static void UpdateOrderStatus(SCSService.Customer_Order order)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            cartSvc.UpdateOrderStatus(order);
        }

        public static int CreatePayment(SCSService.Payment pay)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            return cartSvc.CreatePayment(pay);
        }

        public static List<SCSService.Product> GetListProductByOrderID(int orderID)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            return cartSvc.GetListProductByOrderID(orderID);
        }

        public static SCSService.Order_Item GetOrderItemByProductIDandOrderID(int id, int orderID)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            return cartSvc.GetOrderItemByProductIDandOrderID(id,orderID);
        }

        public static List<SCSService.Product_Stock_Detail> GetListStockDetailByOrderItem(int id)
        {
            SCSService.CartService cartSvc = new SCSService.CartService();
            return cartSvc.GetListStockDetailByOrderItem(id);
        }
        #endregion

        public static Customer GetCustomerByID(int id)
        {
            CartService cartSvc = new CartService();
            return cartSvc.GetCustomerByID(id);
        }

        public static Customer GetCustomerByUserID(int id)
        {
            CartService cartSvc = new CartService();
            return cartSvc.GetCustomerByUserID(id);
        }

        public static List<Rate> GetListRateByType(int type)
        {
            CartService cartSvc = new CartService();
            return cartSvc.GetListRateByType(type);
        }

        public static double? GetRateValueBymoney(float money, int type)
        {
            CartService cartSvc = new CartService();
            return cartSvc.GetRateValueBymoney(money,type);
        }
    }
}